var express = require('express');
var router = express.Router();
const acountMoudel = require('../module/bookmodule');

const low =   require('lowdb');
const FileSync = require('lowdb/adapters/FileSync');
const moment = require('moment'); 
const adapter = new FileSync( __dirname + '/../db/db.json');
// const  db = low(adapter);

let checkLoginMiddleware = (req,res,next)=>{
  if(!req.session.username){
      return res.redirect('/login');
  }
  next();

}

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});
router.get('/account/result', function(req, res, next) {
  res.render('result', {});
});

router.get('/account/add',checkLoginMiddleware, function(req, res, next) {
  // 多模块视图名区分问题：
  res.render('add', {});
});

router.get('/account/list', function(req, res, next) {
  //  let accounts = db.get('accounts').value();
   acountMoudel.find().then((data)=>{
    data.forEach((item)=>{
        item.time = moment(item.time).format('YYYY-MM-dd');
    });

    res.render('list', { accounts:data });
  }).catch((err)=>{
        console.log(err);
    });

});

router.get('/login', function(req, res, next) {
  res.render('login', {});
});


module.exports = router;
